<?php

namespace App\Services\Huanxin;

class ChatServices extends BaseService
{
    /**
     * 发送文本消息
     * $target_type 发送的目标类型；users：给用户发消息，chatgroups：给群发消息，chatrooms：给聊天室发消息
     * $target（逗号隔开的用户环信ID）    tangfen7,tangfen8
     * $from   表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
     * $contents 发送的内容
     * return false 或者true
     */
    public function sendText($target_type, $target, $contents, $from = 'admin')
    {
        if (empty($target_type) || empty($target) || empty($contents)) {
            return false;
        }
        $url = $this->url . 'messages';
        $body['target_type'] = $target_type;
        $body['target'] = [$target];//数组的形式(多个逗号隔开)  tangfen7,tangfen8
        $options['type'] = "txt";
        $options['msg'] = $contents;
        $body['msg'] = $options;
        $body['from'] = $from;
        $b = json_encode($body);
        $header = array($this->getToken());
        $data = postCurl($url, $b, $header);
        return resultHuanxinInfo($data);
    }

    /**
     * 发图片消息
     * $target_type 发送的目标类型；users：给用户发消息，chatgroups：给群发消息，chatrooms：给聊天室发消息
     * $target（逗号隔开的用户环信ID）    tangfen7,tangfen8
     * $from   表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
     * $filePath 上传图片绝对路劲
     * return false 或者true
     */
    public function sendImg($target_type, $target, $filePath, $from = 'admin')
    {
        if (empty($filePath) || empty($from) || empty($target_type) || empty($target)) {
            return false;
        }
        $fileInfo = saveFile($filePath);//上传图片
        $result = $this->uploadFile($fileInfo['tempPath']);
        $uri = $result['uri'];
        $uuid = $result['entities'][0]['uuid'];
        $shareSecret = $result['entities'][0]['share-secret'];
        $url = $this->url . 'messages';
        $body['target_type'] = $target_type;
        $body['target'] = [$target];//数组的形式(多个逗号隔开)
        $options['type'] = "img";
        $options['url'] = $uri . '/' . $uuid;
        $options['filename'] = $fileInfo['fileName'];
        $options['secret'] = $shareSecret;
        $options['size'] = array(
            "width" => 480,
            "height" => 720
        );
        $body['msg'] = $options;
        $body['from'] = $from;
        $header = array($this->getToken());
        $b = json_encode($body, true);
        $data = postCurl($url, $b, $header);
        return resultHuanxinInfo($data);
    }

    /**
     * 上传图片或文件
     * @param $filePath
     * @return bool|mixed|string
     */
    public function uploadFile($filePath)
    {
        $url = $this->url . 'chatfiles';
        $file = file_get_contents($filePath);
        $body['file'] = $file;
        $header = array('Content-type: multipart/form-data', $this->getToken(), "restrict-access:true");
        $result = postCurl($url, $body, $header, 'XXX');
        return $result;
    }

    /**
     * 发送语音消息
     * @param $target_type  发送的目标类型；users：给用户发消息，chatgroups：给群发消息，chatrooms：给聊天室发消息
     * @param $target（逗号隔开的用户环信ID）    tangfen7,tangfen8
     * @param $filePath 上传图片绝对路劲
     * @param string $from 表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
     * @param $filename 语音名称
     * @param string $type
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function sendVoice($target_type, $target, $filePath, $from = 'admin', $filename)
    {
        if (empty($filePath) || empty($from) || empty($target_type) || empty($target) || empty($filename)) {
            return false;
        }
        $result = $this->uploadFile($filePath);
        $uri = $result['uri'];
        $uuid = $result['entities'][0]['uuid'];
        $shareSecret = $result['entities'][0]['share-secret'];
        $url = $this->url . 'messages';
        $body['target_type'] = $target_type;
        $body['target'] = [$target];//数组的形式(多个逗号隔开)
        $options['type'] = "audio";
        $options['url'] = $uri . '/' . $uuid;
        $options['filename'] = $filename;
        $options['secret'] = $shareSecret;
        $body['msg'] = $options;
        $body['from'] = $from;
        $b = json_encode($body);
        $header = array($this->getToken());
        //$b=json_encode($body,true);
        $data = postCurl($url, $b, $header);
        return resultHuanxinInfo($data);
    }

    /**
     * 发送视频消息
     * $target_type 发送的目标类型；users：给用户发消息，chatgroups：给群发消息，chatrooms：给聊天室发消息
     * $target（逗号隔开的用户环信ID）    tangfen7,tangfen8
     * $from   表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
     * $filePath 上传视频的绝对路劲
     * return false 或者true
     */
    public function sendVideo($filePath, $target_type, $target, $filename, $from = 'admin')
    {
        if (empty($filePath) || empty($from) || empty($target_type) || empty($target) || empty($filename)) {
            return false;
        }
        $result = $this->uploadFile($filePath);
        $uri = $result['uri'];
        $uuid = $result['entities'][0]['uuid'];
        $shareSecret = $result['entities'][0]['share-secret'];
        $url = $this->url . 'messages';
        $body['target_type'] = $target_type;
        $body['target'] = [$target];
        $options['type'] = "video";
        $options['url'] = $uri . '/' . $uuid;
        $options['filename'] = $filename;
        $options['secret'] = $shareSecret;
        $body['msg'] = $options;
        $body['from'] = $from;
        $b = json_encode($body);
        $header = array($this->getToken());
        $data = postCurl($url, $b, $header);
        return resultHuanxinInfo($data);
    }

    /**
     * 发送位置消息
     * $target_type 发送的目标类型；users：给用户发消息，chatgroups：给群发消息，chatrooms：给聊天室发消息
     * $target（逗号隔开的用户环信ID）    tangfen7,tangfen8
     * $from   表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
     * return false 或者true
     */
    public function sendPosition($target_type, $target, $from = 'admin')
    {
        if (empty($from) || empty($target_type) || empty($target)) {
            return false;
        }
        $url = $this->url . 'messages';
        $body['target_type'] = $target_type;
        $body['target'] = [$target];
        $options['type'] = "loc";
        $body['msg'] = $options;
        $body['from'] = $from;
        $b = json_encode($body);
        $header = array($this->getToken());
        $data = postCurl($url, $b, $header);
        return resultHuanxinInfo($data);
    }

    /**
     * 发送透传消息
     * $target_type 发送的目标类型；users：给用户发消息，chatgroups：给群发消息，chatrooms：给聊天室发消息
     * $target（逗号隔开的用户环信ID）    tangfen7,tangfen8
     * $msg 消息内容
     * $type
     * $from   表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
     * return false 或者true
     */
    public function sendCmdMessage($target_type, $target, $content, $from = 'admin')
    {
        if (empty($from) || empty($target_type) || empty($target)) {
            return false;
        }
        $url = $this->url . 'messages';
        $body['target_type'] = $target_type;
        $body['target'] = [$target];
        $options['type'] = "cmd";
        $options['msg'] = $content;
        $body['msg'] = $options;
        $body['from'] = $from;
        $b = json_encode($body);
        $header = array($this->getToken());
        $data = postCurl($url, $b, $header);
        return resultHuanxinInfo($data);
    }

    /**
     * @param $time查询的时间格式为10位数字形式 (YYYYMMDDHH),例如要查询2016年12月10号7点到8点的历史记录，则需要输入2016121007,7:00:00的信息也会包含在这个文件里
     * 因为历史记录文件生成需要一定时间，建议用户在取得历史记录时要间隔一个小时，例如2016/12/10 09:00之后，可以开始下载2016/12/10 07:00 ～ 08:00的消息历史记录
     * 接口返回的下载地址30分钟内有效
     *author:tangfen
     *date:$ct
     */
    public function getChatRecord($time)
    {
        $url = $this->url . 'chatmessages/' . $time;
        $header = array($this->getToken());
        $data = postCurl($url, '', $header, "GET");
        return resultHuanxinInfo($data);
    }

    /**
     *环信即时推送
     * @param $targets im 用户名。最大可传100个
     * @param $pushMessage 推送的内容
     *author:tangfen
     *date:$ct
     */
    public function pushMessage($targets,$title,$contents)
    {
        if (empty($targets) || empty($contents)|| empty($title)) {
            return false;
        }
        $body = [
            'targets' => [$targets],
//            'async' => true,  //是否异步推送。默认：异步 说明： 同步推送，推送target数量为1 异步推送，推送target数量为100
//            'strategy' => 1,       //推送策略。默认：2。说明：0-厂商通道优先，然后环信通道，1-环信通道，2-三方通道，3-环信通道优先，然后三方
            "pushMessage" => [
                'title' =>$title,
                'content' =>$contents,
                'iconUrl'=> ''  ,//	string	图标的URL
                'sound'=>1,     //声音，默认：0无声音，为1则声音提醒	iOS&Android
                'vibrate'=>1,   //integer	震动，默认：0无震动，为1则震动提醒 iOS&Android
            ]
        ];
        $body = json_encode($body);
        $header = array(
            $this->getToken(),
            'Content-type:application/json'
        );
        $url = $this->url . 'push/single';
        $data = postCurl($url, $body, $header, 'POST');
        return resultHuanxinInfo($data);
    }

}
